package com.wulab.backend.serviceImpl;


import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wulab.backend.entity.Dataset;
import com.wulab.backend.mapper.DatasetMapper;
import com.wulab.backend.service.DatasetService;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

@Service
public class DatasetServiceImpl extends ServiceImpl<DatasetMapper, Dataset> implements DatasetService {

    @Autowired
    private DatasetMapper datasetMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void importDataset(MultipartFile file) throws Exception {
        InputStream inputStream = file.getInputStream();

        // 使用 Apache POI 解析 Excel 文件
        Workbook workbook = new XSSFWorkbook(inputStream);
        Sheet sheet = workbook.getSheetAt(0);  // 获取第一个工作表

        List<Dataset> datasets = new ArrayList<>();

        for (int i = 1; i <= sheet.getPhysicalNumberOfRows(); i++) {
            Row row = sheet.getRow(i);
            if (row == null) continue;

            // 读取每一行的单元格
            Dataset dataset = new Dataset();
            dataset.setDatasets(row.getCell(0).getStringCellValue());  // 第1列
            dataset.setReference(row.getCell(1).getStringCellValue());  // 第2列
            dataset.setSampleType(row.getCell(2).getStringCellValue()); // 第3列
            dataset.setSampleNum((int) row.getCell(3).getNumericCellValue());  // 第4列
            dataset.setEnzyme(row.getCell(4).getStringCellValue());  // 第5列

            datasets.add(dataset);
        }

        // 将数据保存到数据库
        saveBatch(datasets);
    }

    @Override
    public List<Dataset> getDatasets() {
        return datasetMapper.selectList(null);
    }

}
